import React, { useEffect, useState } from 'react';
import { Card, Form, Button, Alert } from 'react-bootstrap';

const LogManagement = ({ config, setConfig }) => {
  // 组件内部默认配置
  const defaultLogConfig = {
    logLevel: 'INFO',
    logFileSizeLimit: 10,
    enableConsoleLogging: true,
    enableFileLogging: true,
    doLogs: false,
    adminLog: false,
    adminLogPlayerHitsOnly: false,
    adminLogPlacement: false,
    adminLogRemove: false,
    adminLogKill: false,
    adminLogChat: false,
    netLog: false
  };

  // 组件内部状态，用于表单输入临时存储
  const [localConfig, setLocalConfig] = useState(defaultLogConfig);
  const [logs, setLogs] = useState([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [logsError, setLogsError] = useState('');

  // 当外部config变化时，更新内部localConfig
  useEffect(() => {
    const mergedConfig = {
      ...defaultLogConfig,
      ...config
    };
    setLocalConfig(mergedConfig);
  }, [config]);

  // 处理配置变更，同时更新本地状态和全局配置
  const handleConfigChange = (key, value) => {
    const updatedLocalConfig = {
      ...localConfig,
      [key]: value
    };
    setLocalConfig(updatedLocalConfig);
    
    setConfig({
      ...config,
      [key]: value
    });
  };

  // 模拟加载日志函数
  const loadLogs = async () => {
    setLogsLoading(true);
    setLogsError('');
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockLogs = [
        '2024-01-01 10:00:00 [INFO] 服务器启动成功',
        '2024-01-01 10:01:00 [INFO] 玩家 Player1 加入服务器',
        '2024-01-01 10:02:00 [WARNING] 高延迟警告: Player1 (ping: 200ms)',
        '2024-01-01 10:03:00 [INFO] 玩家 Player2 加入服务器'
      ];
      setLogs(mockLogs);
    } catch (error) {
      setLogsError('加载日志失败: ' + error.message);
    } finally {
      setLogsLoading(false);
    }
  };

  // 清空日志
  const clearLogs = () => {
    setLogs([]);
    setLogsError('');
  };

  return (
    <Card className="h-100 border-3 shadow-medium" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(15px)', borderColor: '#d32f2f', boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 0 10px rgba(211, 47, 47, 0.2)'}}>
      <Card.Header style={{backgroundColor: 'rgba(40, 40, 40, 0.7)', backdropFilter: 'blur(15px)'}}>
        <h3 style={{color: 'var(--primary-color)'}}>日志管理</h3>
      </Card.Header>
      <Card.Body style={{color: '#ffffff', maxHeight: '70vh', overflowY: 'auto'}}>
        <div className="row mb-4">
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>日志级别</Form.Label>
              <Form.Select 
                value={localConfig.logLevel}
                onChange={(e) => handleConfigChange('logLevel', e.target.value)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}} 
              >
                <option value="DEBUG">DEBUG</option>
                <option value="INFO">INFO</option>
                <option value="WARNING">WARNING</option>
                <option value="ERROR">ERROR</option>
                <option value="CRITICAL">CRITICAL</option>
              </Form.Select>
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                设置日志记录的最低级别
              </Form.Text>
            </Form.Group>
          </div>
          <div className="col-md-6">
            <Form.Group className="mb-3">
              <Form.Label>日志文件大小限制（MB）</Form.Label>
              <Form.Control 
                type="number" 
                min="1" 
                value={localConfig.logFileSizeLimit}
                onChange={(e) => handleConfigChange('logFileSizeLimit', parseInt(e.target.value) || 10)} 
                className="glass-input"
                style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}} 
              />
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                单个日志文件的最大大小（MB）
              </Form.Text>
            </Form.Group>
          </div>
        </div>
        
        <div className="mb-4">
          <Form.Group className="mb-3">
            <Form.Check 
              type="switch" 
              checked={localConfig.enableConsoleLogging}
              onChange={(e) => handleConfigChange('enableConsoleLogging', e.target.checked)} 
              label="启用控制台日志" 
              style={{color: '#ffffff'}} 
            />
            <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
              是否在控制台输出日志
            </Form.Text>
          </Form.Group>
          
          <Form.Group className="mb-3">
            <Form.Check 
              type="switch" 
              checked={localConfig.enableFileLogging}
              onChange={(e) => handleConfigChange('enableFileLogging', e.target.checked)} 
              label="启用文件日志" 
              style={{color: '#ffffff'}} 
            />
            <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
              是否将日志写入文件
            </Form.Text>
          </Form.Group>

          <Form.Group className="mb-3">
            <Form.Check 
              type="switch" 
              checked={localConfig.doLogs}
              onChange={(e) => handleConfigChange('doLogs', e.target.checked)} 
              label="启用基础日志记录" 
              style={{color: '#ffffff'}} 
            />
            <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
              启用基础服务器日志记录
            </Form.Text>
          </Form.Group>

          <Form.Group className="mb-3">
            <Form.Check 
              type="switch" 
              checked={localConfig.adminLog}
              onChange={(e) => handleConfigChange('adminLog', e.target.checked)} 
              label="启用管理员日志" 
              style={{color: '#ffffff'}} 
            />
            <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
              记录管理员操作日志
            </Form.Text>
          </Form.Group>

          <Form.Group className="mb-3">
            <Form.Check 
              type="switch" 
              checked={localConfig.netLog}
              onChange={(e) => handleConfigChange('netLog', e.target.checked)} 
              label="启用网络日志" 
              style={{color: '#ffffff'}} 
            />
            <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
              记录网络连接日志
            </Form.Text>
          </Form.Group>
        </div>

        {/* 管理员日志详细配置 */}
        <div className="admin-log-config mb-4" style={{marginTop: '15px', padding: '15px', backgroundColor: 'rgba(255,255,255,0.05)', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.1)'}}>
          <h5 style={{color: '#4dabf7', marginBottom: '10px', fontSize: '1rem'}}>管理员日志配置</h5>
          
          <Form.Group className="mb-2">
            <Form.Check 
              type="switch" 
              label="仅记录玩家伤害" 
              checked={localConfig.adminLogPlayerHitsOnly} 
              onChange={(e) => handleConfigChange('adminLogPlayerHitsOnly', e.target.checked)} 
              className="form-switch-glow"
            />
          </Form.Group>
          
          <Form.Group className="mb-2">
            <Form.Check 
              type="switch" 
              label="记录放置物品" 
              checked={localConfig.adminLogPlacement} 
              onChange={(e) => handleConfigChange('adminLogPlacement', e.target.checked)} 
              className="form-switch-glow"
            />
          </Form.Group>
          
          <Form.Group className="mb-2">
            <Form.Check 
              type="switch" 
              label="记录移除物品" 
              checked={localConfig.adminLogRemove} 
              onChange={(e) => handleConfigChange('adminLogRemove', e.target.checked)} 
              className="form-switch-glow"
            />
          </Form.Group>
          
          <Form.Group className="mb-2">
            <Form.Check 
              type="switch" 
              label="记录击杀" 
              checked={localConfig.adminLogKill} 
              onChange={(e) => handleConfigChange('adminLogKill', e.target.checked)} 
              className="form-switch-glow"
            />
          </Form.Group>
          
          <Form.Group className="mb-2">
            <Form.Check 
              type="switch" 
              label="记录聊天" 
              checked={localConfig.adminLogChat} 
              onChange={(e) => handleConfigChange('adminLogChat', e.target.checked)} 
              className="form-switch-glow"
            />
          </Form.Group>
          
          <div className="row mt-4">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>FPS日志频率</Form.Label>
                <Form.Control
                  type="number"
                  value={localConfig.logAverageFps || 0}
                  onChange={(e) => handleConfigChange('logAverageFps', parseInt(e.target.value) || 0)}
                  min="0"
                  max="300"
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  0表示禁用FPS日志
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>内存日志频率</Form.Label>
                <Form.Control
                  type="number"
                  value={localConfig.logMemory || 0}
                  onChange={(e) => handleConfigChange('logMemory', parseInt(e.target.value) || 0)}
                  min="0"
                  max="300"
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  0表示禁用内存日志
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>玩家日志频率</Form.Label>
                <Form.Control
                  type="number"
                  value={localConfig.logPlayers || 0}
                  onChange={(e) => handleConfigChange('logPlayers', parseInt(e.target.value) || 0)}
                  min="0"
                  max="300"
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  0表示禁用玩家日志
                </Form.Text>
              </Form.Group>
            </div>
          </div>
        </div>

        <div className="mb-4">
          <div className="d-flex justify-content-between align-items-center mb-3">
            <h4 style={{color: '#ffffff', margin: 0}}>查看日志</h4>
            <div>
              <Button 
                variant="primary" 
                onClick={loadLogs} 
                disabled={logsLoading}
                style={{backgroundColor: '#ff9800', borderColor: '#ff9800', marginRight: '10px'}}
              >
                {logsLoading ? '加载中...' : '加载日志'}
              </Button>
              <Button 
                variant="danger" 
                onClick={clearLogs}
                style={{backgroundColor: '#f44336', borderColor: '#f44336'}}
              >
                清空日志
              </Button>
            </div>
          </div>
          
          {logsError && (
            <Alert variant="danger" style={{backgroundColor: 'rgba(244, 67, 54, 0.2)', borderColor: '#f44336', color: '#ffffff', marginBottom: '15px'}}>
              {logsError}
            </Alert>
          )}
          
          {logs && logs.length > 0 ? (
            <div style={{maxHeight: '300px', overflowY: 'auto', backgroundColor: 'rgba(0,0,0,0.5)', borderRadius: '5px', padding: '10px', fontFamily: 'monospace', fontSize: '12px'}}>
              {logs.map((log, index) => (
                <div key={index} style={{marginBottom: '5px', color: '#ffffff'}}>{log}</div>
              ))}
            </div>
          ) : (
            <p style={{color: '#ffffff', opacity: 0.7}}>暂无日志数据</p>
          )}
        </div>
      </Card.Body>
    </Card>
  );
}

export default LogManagement;